//
//  FillLearningViewController.swift
//  fsapp
//
//  Created by zguang on 17/7/26.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import Alamofire
//import

class FillLearningViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{

    var selectArr:Int?
    var ChildType:[
        String:[String]] = ["id":[],"name":[]]
    let layout = UICollectionViewFlowLayout()
    var collectionView: UICollectionView?
    var selectFlag:String?

    var footerRefreshView :FCXRefreshFooterView?
    var page = 2
    let tableview = UITableView()
    let childView = ChildView(type:"fill")
    var moneySort = false
    var timeSort = false
    var countSort = false
    var titleArray = [String]()
    var moneyArray = [String]()
    var timeArray =  [String]()
    var playCout = [String]()
    var likeCount = [String]()
    var commitCount = [String]()
    var starCount = [String]()
    var video_src = [String]()
    var pic_src = [String]()
    var videoID = [String]()
     var newIndex = [Int]()
    var isLike = [String]()
    var isCollection = [String]()
    
    var type = ""
   var refreshControl = UIRefreshControl()
    
    
    init(typee:String) {
        super.init(nibName: nil, bundle: nil)
        self.type = typee
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        Alarequest()
        
        self.tabBarController?.tabBar.isHidden = false
        let dict:NSDictionary = [NSForegroundColorAttributeName: UIColor.white,NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)]
        //标题颜色
        self.navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        self.navigationItem.title = "完整学习"
        self.navigationController?.navigationBar.isTranslucent = false

        self.navigationController?.navigationBar.barTintColor = naviColor

   

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       self.tabBarController?.tabBar.isHidden = false
        refreshControl.addTarget(self, action: #selector(refresh),
                                 for: .valueChanged)
        refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新数据")
        tableview.addSubview(refreshControl)
        
        let item = UIBarButtonItem(image: #imageLiteral(resourceName: "搜索"), style: .plain, target: self, action: #selector(touchSearch))
        //item.imageInsets = UIEdgeInsets.init(top: 10, left: 25, bottom: 10, right: -5)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.rightBarButtonItem = item
      
        

        
        initTV()
        addRefreshView()
        //self.view.addSubview(childView.headerView)
        childView.moneySort.addTarget(self, action: #selector(moneyClick(_:)), for: .touchUpInside)
        childView.countSort.addTarget(self, action: #selector(countClick(_:)), for: .touchUpInside)
        childView.timeSort.addTarget(self, action: #selector(timeClick(_:)), for: .touchUpInside)
        // Do any additional setup after loading the view.
    }
    
    func touchSearch(){
    
      self.navigationController?.pushViewController(SearchViewController(), animated: false)
    }
    
    
    func addRefreshView() {
        footerRefreshView =
        tableview.addFCXRefreshFooter { [weak self] (refreshHeader) in
            self?.loadMoreAction()
        }
    }
    
    func loadMoreAction() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) { [weak self] in
            guard let weakSelf = self,
                let footerRefreshView = self?.footerRefreshView else {
                    return
            }
            
            weakSelf.Alarequest(page: weakSelf.page)
            
           // weakSelf.rows += 20
           // self?.tableview.reloadData()
        }
        
    }
        
        

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func refresh(){
       Alarequest()
}
    
    //MARK: - TableviewDelegate
    func initTV (){
        self.setCollectionView()
        childView.headerView.addSubview(collectionView! )
        self.view.addSubview(childView.headerView)
        tableview.frame = CGRect(x:0,y:getHeight(130),width:SCREEN_WIDTH,height:SCREEN_HEIGHT - (self.navigationController?.navigationBar.frame.height)! - UIApplication.shared.statusBarFrame.height - (self.tabBarController?.tabBar.frame.height)!)
        tableview.delegate = self
        tableview.dataSource = self
        // tableview.backgroundColor = UIColor.blue
        // view.backgroundColor = UIColor.red
        // self.view.addSubview(tableview)
        self.view.addSubview(tableview)
        
    }
    
    //MARK: -  Basic Func
    
    func moneyClick(_ btn:UIButton){
        
   
        
        
        if !btn.isSelected{
//            let anim = CABasicAnimation(keyPath: "transform.rotation")
//            anim.toValue = 1 * M_PI/2
//            anim.duration = 0.2
//            anim.repeatCount = 0
//          //  btn.imageView?.stopAnimating()
//
//            anim.isRemovedOnCompletion = true
//            btn.imageView?.layer.add(anim, forKey: nil)
            //  btn.imageView?.removeAllAnimations()
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
            
            var newplay = [Int]()
            for i in moneyArray{
                let nn = i.components(separatedBy: ".")
                newplay.append(Int(nn[0])!)
            }
            playCountbubbleSort(arr: &newplay)
            self.tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }else{
//            let anim = CABasicAnimation(keyPath: "transform.rotation")
//            anim.toValue =  -(1 * M_PI)/2
//            anim.duration = 0.2
//            anim.repeatCount = 0
//            anim.isRemovedOnCompletion = true
//            btn.imageView?.layer.add(anim, forKey: nil)
        //
           UIView.animate(withDuration: 0.2) {
               btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
          }

            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }
       
    }
    func timeClick(_ btn:UIButton){
        //var ll = "5:20"
    
        
       /// print(Int(newll[0]))
        if !btn.isSelected{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
            var newplay = [Int]()
            for i in timeArray{
                let newll = i.components(separatedBy: ":")
                newplay.append(Int(newll[0])!)
            }
            playCountbubbleSort(arr: &newplay)
            self.tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }else{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
            }
            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
            btn.isSelected = !btn.isSelected
        }
}
    func countClick(_ btn:UIButton){
        if !btn.isSelected{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: CGFloat(M_PI)))!
            }
        var newplay = [Int]()
        for i in playCout{
           newplay.append(Int(i)!)
        }
        playCountbubbleSort(arr: &newplay)
        self.tableview.reloadData()
       btn.isSelected = !btn.isSelected
        }else{
            UIView.animate(withDuration: 0.2) {
                btn.imageView?.transform =  (btn.imageView?.transform.rotated(by: -CGFloat(M_PI)))!
            }
            videoID.reverse()
            titleArray.reverse()
            timeArray.reverse()
            moneyArray.reverse()
            playCout.reverse()
            likeCount.reverse()
            commitCount.reverse()
            starCount.reverse()
            pic_src.reverse()
            video_src.reverse()
            tableview.reloadData()
           btn.isSelected = !btn.isSelected
        }
    }
    
    //冒泡排序
    func playCountbubbleSort( arr: inout [Int]) -> [Int] {
        for i in 0 ..< arr.count {
            for j in 0 ..< arr.count - 1 - i {
                if arr[j] > arr[j + 1] {
                    let temp = arr[j]
                    arr[j] = arr[j + 1]
                    arr[j + 1] = temp
                    let temp2 = videoID[j]
                    videoID[j] = videoID[j+1]
                    videoID[j+1] = temp2
                    
                    let temp3 = titleArray[j]
                    titleArray[j] = titleArray[j+1]
                    titleArray[j+1] = temp3
                    
                    let temp4 = timeArray[j]
                    timeArray[j] = timeArray[j+1]
                    timeArray[j+1] = temp4
                    
                    let temp5 = moneyArray[j]
                    moneyArray[j] = moneyArray[j+1]
                    moneyArray[j+1] = temp5
                    
                    let temp6 = playCout[j]
                    playCout[j] = playCout[j+1]
                    playCout[j+1] = temp6
                    
                    let temp7 = likeCount[j]
                    likeCount[j] = likeCount[j+1]
                    likeCount[j+1] = temp7
                    
                    let temp8 = commitCount[j]
                    commitCount[j] = commitCount[j+1]
                    commitCount[j+1] = temp8
                    
                    let temp9 = starCount[j]
                    starCount[j] = starCount[j+1]
                    starCount[j+1] = temp9
                    
                    let temp10 = pic_src[j]
                    pic_src[j] = pic_src[j+1]
                    pic_src[j+1] = temp10
                    
                    let temp11 = video_src[j]
                    video_src[j] = video_src[j+1]
                    video_src[j+1] = temp11
                }
                
            }
        }
        return arr
    }
    
    
    
    
    
    func clickLike(_ btn:UIButton){
        if btn.isSelected {
            btn.isSelected = false
        }else{
            btn.isSelected = true
        }
    
    }
    
    
    
    
    
    
    // MARK: - tableview 代理
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArray.count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return getHeight(483)
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = FillLearnTableViewCell(style:.default,reuseIdentifier:"cell")
        
        
        cell.playButton.tag = indexPath.row
        cell.playButton.addTarget(self, action: #selector(touchplaycell(_:)), for: .touchUpInside)
        
        cell.title.text = titleArray[indexPath.row]
        cell.timeSpan.text = timeArray[indexPath.row]
        cell.money.text = "¥ " + moneyArray[indexPath.row]
        cell.backImage.imageFromURL(pic_src[indexPath.row], placeholder: #imageLiteral(resourceName: "test"))
        cell.videoCount.setTitle(playCout[indexPath.row
            ], for: .normal)
        cell.likeCount.setTitle(likeCount[indexPath.row], for: .normal)
        cell.coommitCount.setTitle(commitCount[indexPath.row], for: .normal)
        cell.starCount.setTitle(starCount[indexPath.row], for: .normal)
        if indexPath.row <=  isCollection.count{
        if isCollection[indexPath.row] == "1"{
           cell.starCount.isSelected = true
        }
        if isLike[indexPath.row] == "1" {
           cell.likeCount.isSelected = true
        }
        
        }
        
        
        
        return cell
        
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       // self.hidesBottomBarWhenPushed = true

        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        self.tabBarController?.tabBar.isHidden = true
        self.present(VideoDetailViewController(self.video_src[indexPath.row],self.videoID[indexPath.row]), animated: true, completion: nil)
        //  self.navigationController?.pushViewController(VideoDetailViewController(self.video_src[indexPath.row],self.videoID[indexPath.row]), animated: true)
        
    }
    
    func touchplaycell(_ btn:UIButton){
        //self.hidesBottomBarWhenPushed = true

        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"",style:.plain,target:nil,action:nil)
        self.navigationController?.pushViewController(VideoDetailViewController(self.video_src[btn.tag],self.videoID[btn.tag]), animated: true)

    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
         //MARK:XG
        return getHeight(0)
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        //let view = UIView(frame: view.frame)
        //view.addSubview(sliderGallery.view)
        //MARK:XG
        
        
        return nil
    }
    

    
    //MARK: - 网络请求
    
    func Alarequest(){
        self.page = 2
        let url = "http://dahan-api.heiyou.net/index.php/home/index/type"
        //MARK: XG
        let paramdic:[String:String] = {
            if self.selectFlag == nil{
               let make = ["type":type,"page":"1","limit":"10"]
               return make
            }else{
                let make = ["type":type,"page":"1","limit":"10","child_type":selectFlag]
                return make as! [String : String]
            }
        }()
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
           // print("result=========================")
           // print(response.request)  // original URL request
            //print(response.response) // HTTP URL response
            //print(response.data)     // server data
            //print(response.result)   // result of response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
              //  print(js)
              //  self.resultJson = js
                
                var newtitleArray = [String]()
                var newmoneyArray = [String]()
                var newtimeArray =  [String]()
                var newplayCout = [String]()
                var newlikeCount = [String]()
                var newcommitCount = [String]()
                var newstarCount = [String]()
                var newvideo_src = [String]()
                var newpic_src = [String]()
                var newID = [String]()
                var newlike = [String]()
                var newcollect = [String]()
                
                if js["length"].int != 0{
                    for i in 0...js["length"].int!-1{
                        newtitleArray.append(js["result"][i]["name"].string!)
                        newmoneyArray.append(js["result"][i]["price"].string!)
                        if let arr = js["result"][i]["duration"].string{
                            newtimeArray.append(arr)
                        }else{
                            newtimeArray.append("0")
                        }
                        newpic_src.append(js["result"][i]["pic_src"].string!)
                        newvideo_src.append(js["result"][i]["video_src"].string!)
                        newplayCout.append(js["result"][i]["play"].string!)
                        newlikeCount.append(js["result"][i]["good"].string!)
                        newcommitCount.append(js["result"][i]["comment"].string!)
                        if let arr = js["result"][i]["nums"].string{
                            newstarCount.append(arr)}
                        else{
                            newstarCount.append("0")
                           }
                        newID.append(js["result"][i]["id"].string!)
                        if let like =  js["result"][i]["actionPoint"].string{
                            newlike.append(like)
                            
                        }else{
                            newlike.append("")
                        }
                        if let collected =  js["result"][i]["actionCollection"].string{
                            newcollect.append(collected)
                        }else{
                            newcollect.append("")
                        }

                        
                        
                    }
                    
                    self.titleArray = newtitleArray
                    self.timeArray = newtimeArray
                    self.moneyArray = newmoneyArray
                    self.pic_src = newpic_src
                    self.video_src = newvideo_src
                    self.commitCount = newcommitCount
                    self.likeCount = newlikeCount
                    self.commitCount = newcommitCount
                    self.starCount = newstarCount
                    self.playCout = newplayCout
                    self.videoID = newID
                    self.isLike = newlike
                    self.isCollection = newcollect
                    //self.footerRefreshView?.endRefresh()
                    self.refreshControl.endRefreshing()
                    self.tableview.reloadData()
                    }
                    
                }else{
                
                    self.footerRefreshView?.showNoMoreData();
               

                }

                
                
            }
            
        
    }
    
    func Alarequest(page:Int){
        let url = "http://dahan-api.heiyou.net/index.php/home/index/type"
        let paramdic = ["type":type,"page":"\(page)","limit":"10"]
       // let current = page
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
//            print("result=========================")
//            print(response.request)  // original URL request
//            print(response.response) // HTTP URL response
//            print(response.data)     // server data
//            print(response.result)   // result of response serialization
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                // print(js)
               
                
                if js["length"].int != 0{
                    
                    self.page += 1
                    for i in 0...js["length"].int!-1{
                        self.titleArray.append(js["result"][i]["name"].string!);
                        self.moneyArray.append(js["result"][i]["price"].string!);
                        if let arr = js["result"][i]["duration"].string{
                            self.timeArray.append(arr)
                        }else{
                            self.timeArray.append("0")
                        }
                        self.pic_src.append(js["result"][i]["pic_src"].string!)
                        self.video_src.append(js["result"][i]["video_src"].string!)
                        self.playCout.append(js["result"][i]["play"].string!)
                        self.likeCount.append(js["result"][i]["good"].string!)
                        self.commitCount.append(js["result"][i]["comment"].string!);
                        if let arr = js["result"][i]["nums"].string{
                            self.starCount.append(arr)}
                        else{
                            self.starCount.append("0")
                        }
                        self.videoID.append(js["result"][i]["id"].string!)
                        if let like =  js["result"][i]["actionPoint"].string{
                            self.isLike.append(like)
                            
                        }else{
                            self.isLike.append("")
                        }
                        if let collected =  js["result"][i]["actionCollection"].string{
                            self.isCollection.append(collected)
                        }else{
                            self.isCollection.append("")
                        }
           
                    }
                    self.footerRefreshView?.endRefresh()
                    self.tableview.reloadData()
                    
                }else{
                   
                    self.footerRefreshView?.showNoMoreData()
                
                }
                
                
                
            }
            
        }
    }
    


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
